package com.example.demo.Controller;

import com.example.demo.Bean.Member;
import com.example.demo.Bean.Shop;
import com.example.demo.Bean.User;
import com.example.demo.Service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RegisterController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Boolean register(String username,String mail,String password){
        User user = userService.queryUserByName(username);
        try{
            user.getUsername();
            return false;
        }catch (Exception e){
            String md5 = username + password;
            byte[] bytes = md5.getBytes();
            String pwd = DigestUtils.md5DigestAsHex(bytes);
            User user1 = new User();
            user1.setUsername(username);
            user1.setPassword(pwd);
            user1.setMail(mail);
            userService.insertUser(user1);
            Member member = new Member();
            member.setUsername(username);
            member.setEmail(mail);
            rabbitTemplate.convertAndSend("email.fanout", "", member);
            System.out.println("AMOP发送成功");
            return true;
        }
    }

    @PostMapping("/shopregister")
    public Boolean shopregister(String name,String mail,String password,String boss,String address){
        Shop shopByName = userService.getShopByName(name);
        try{
            shopByName.getShop();
            return false;
        }catch (Exception e){
            String md5 = name + password;
            byte[] bytes = md5.getBytes();
            String pwd = DigestUtils.md5DigestAsHex(bytes);
            Shop shop = new Shop();
            shop.setShop(name);
            shop.setEmail(mail);
            shop.setPassword(pwd);
            shop.setBoss(boss);
            shop.setAddress(address);
            userService.insertShop(shop);
            return true;
        }
    }
}
